﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;


namespace tswe.umbraco.languageEditor.classes.xml
{
    public class Area
    {
        [XmlAttribute(AttributeName = "alias", DataType = "string")]
        public string Alias;

        [XmlElement("key", typeof(Key))]
        public List<Key> Keys = new List<Key>();

        /// <summary>
        /// tidy up this area keys to match other areas order
        /// and will remove empty keys
        /// </summary>
        /// <param name="other"></param>
        /// <returns>false: this area has no keys inside</returns>
        public bool TidyUpBy(Area other)
        {
            bool hasKey = false;
            int index = 0;
            foreach (Key otherKey in other.Keys)
            {
                int keyIndex = findIndex(otherKey.Alias);
                if (keyIndex < 0) continue;

                Key thisKey = Keys[keyIndex];
                Keys.RemoveAt(keyIndex);

                string value = thisKey.Value;
                if (value != null)
                    value = value.Trim();
                if (String.IsNullOrEmpty(value)) continue;

                Keys.Insert(index, thisKey);
                hasKey = true;
                index++;
            }
            return hasKey;
        }

        private int findIndex(string alias)
        {
            int index = 0;
            foreach (Key key in Keys)
            {
                if (key.Alias == alias)
                    return index;
                index++;
            }
            return -1;
        }
    }

}
